package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import repositorios.IRepUsuario;
import repositorios.RepUsuario;

import controladores.CtrlUsuario;
import entidades.Usuario;

/**
 * Servlet implementation class ServletControlador
 */
public class ServletControlador extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private CtrlUsuario ctrlUsuario;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletControlador() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init() throws ServletException {
		super.init();
		IRepUsuario repUsuario = new RepUsuario();
		ctrlUsuario = new CtrlUsuario(repUsuario);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String cmd = request.getParameter("cmd");

		if (cmd != null && cmd.equals("login")) {
			login(request, response);
		}else{
			irParaPagina(request, response, "index.jsp");
		}
	}

	private void login(HttpServletRequest request, HttpServletResponse response) {
		String email = request.getParameter("email");
		String senha = request.getParameter("senha");
		
		try {
			Usuario usuario = ctrlUsuario.consultar(email);
			if (usuario != null && email.equals(usuario.getEmail())
					&& senha.equals(usuario.getSenha())) {
				
				HttpSession session = request.getSession(true);
				session.setAttribute("usuario", new Usuario(email, senha));
				
				irParaPagina(request, response, "login.jsp");
				
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private void irParaPagina(HttpServletRequest request,
			HttpServletResponse response, String para) {
		
		ServletContext sc = this.getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(para);
		
		try {
			rd.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
